<template>
    <div class="flex align-items-center">
      <template v-if="src">
        <div class="mr-2 flex-1" :style="{height, width}">
          <div class="pdf-container" @click="openPDF">
            <div class="pdf-preview-container">
              <i class="pi pi-file-pdf text-4xl"></i>
              <div class="pdf-filename">{{ getFilename() }}</div>
            </div>
          </div>
        </div>
      </template>
      <div v-else :style="{width, height}" class="flex justify-content-center align-items-center text-center surface-100 p-2 border-round">
        <i class="text-400 pi pi-file text-4xl"></i>
      </div>
  
      <Dialog 
        v-model:visible="pdfDialogVisible" 
        :style="{width: '95vw', height: '95vh'}" 
        :maximizable="true"
        :modal="true"
        class="pdf-dialog"
        header="PDF预览">
        <div class="pdf-dialog-container">
          <iframe 
            v-if="pdfDialogVisible" 
            :src="pdfUrl" 
            class="pdf-viewer"
            frameborder="0">
          </iframe>
        </div>
        <template #footer>
          <Button label="关闭" icon="pi pi-times" @click="pdfDialogVisible = false" class="p-button-text"/>
          <Button label="下载" icon="pi pi-download" @click="downloadPDF" class="p-button-primary"/>
          <Button label="适合页面" icon="pi pi-window-maximize" @click="fitToPage" class="p-button-secondary"/>
          <Button label="全屏" icon="pi pi-window-maximize" @click="toggleFullscreen" class="p-button-secondary"/>
        </template>
      </Dialog>
    </div>
  </template>
  
  <script>
  import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
  import { useAppStore } from 'src/store/app';
  
  export default {
    props: {
      src: {
        type: String,
      },
      width: {
        type: String,
        default: '150px'
      },
      height: {
        type: String,
        default: '200px'
      },
      pageNum: {
        type: Number,
        default: 1
      }
    },
    setup(props) {
      const app = useAppStore();
      const pdfDialogVisible = ref(false);
      const isFullscreen = ref(false);
      const scale = ref(1.0);
      const pdfFrameRef = ref(null);
      
      // 计算PDF的完整URL
      const pdfUrl = computed(() => {
        if (!props.src) return '';
        // 添加时间戳防止缓存和scale参数
        return `http://localhost:8060/${props.src}?t=${Date.now()}#view=FitH`;
      });
      
      // 从路径中提取文件名
      const getFilename = () => {
        if (!props.src) return 'PDF文件';
        const parts = props.src.split('/');
        let filename = parts[parts.length - 1];
        // 如果文件名太长，截取显示
        if (filename.length > 15) {
          filename = filename.substring(0, 12) + '...';
        }
        return filename;
      };
      
      // 打开PDF预览对话框
      const openPDF = () => {
        pdfDialogVisible.value = true;
      };
      
      // 下载PDF文件
      const downloadPDF = () => {
        if (!props.src) return;
        
        // 创建一个临时的a标签
        const link = document.createElement('a');
        link.href = `http://localhost:8060/${props.src}`;
        link.download = getFilename(); // 指定下载的文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      };
      
      // 放大PDF
      const zoomIn = () => {
        try {
          const frame = document.querySelector('.pdf-viewer');
          if (frame && frame.contentWindow) {
            frame.contentWindow.postMessage({ action: 'zoomIn' }, '*');
          }
        } catch (e) {
          console.error('缩放失败:', e);
        }
      };
      
      // 缩小PDF
      const zoomOut = () => {
        try {
          const frame = document.querySelector('.pdf-viewer');
          if (frame && frame.contentWindow) {
            frame.contentWindow.postMessage({ action: 'zoomOut' }, '*');
          }
        } catch (e) {
          console.error('缩放失败:', e);
        }
      };
      
      // 适合页面
      const fitToPage = () => {
        try {
          const frame = document.querySelector('.pdf-viewer');
          if (frame && frame.contentWindow) {
            frame.contentWindow.postMessage({ action: 'fitToPage' }, '*');
          }
        } catch (e) {
          console.error('适合页面失败:', e);
        }
      };
      
      // 切换全屏模式
      const toggleFullscreen = () => {
        const pdfViewer = document.querySelector('.pdf-dialog');
        
        if (!isFullscreen.value) {
          if (pdfViewer.requestFullscreen) {
            pdfViewer.requestFullscreen();
          } else if (pdfViewer.mozRequestFullScreen) { /* Firefox */
            pdfViewer.mozRequestFullScreen();
          } else if (pdfViewer.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
            pdfViewer.webkitRequestFullscreen();
          } else if (pdfViewer.msRequestFullscreen) { /* IE/Edge */
            pdfViewer.msRequestFullscreen();
          }
        } else {
          if (document.exitFullscreen) {
            document.exitFullscreen();
          } else if (document.mozCancelFullScreen) { /* Firefox */
            document.mozCancelFullScreen();
          } else if (document.webkitExitFullscreen) { /* Chrome, Safari & Opera */
            document.webkitExitFullscreen();
          } else if (document.msExitFullscreen) { /* IE/Edge */
            document.msExitFullscreen();
          }
        }
        
        isFullscreen.value = !isFullscreen.value;
      };
      
      // 监听全屏状态变化
      const fullscreenChangeHandler = () => {
        isFullscreen.value = !!document.fullscreenElement;
      };
      
      // 监听来自iframe的消息
      const messageHandler = (event) => {
        // 处理从PDF查看器发来的消息
        if (event.data && event.data.type === 'pdfLoaded') {
          // PDF已加载完成
          console.log('PDF加载完成');
        }
      };
      
      onMounted(() => {
        if (typeof document !== 'undefined') {
          document.addEventListener('fullscreenchange', fullscreenChangeHandler);
          window.addEventListener('message', messageHandler);
        }
      });
      
      onBeforeUnmount(() => {
        if (typeof document !== 'undefined') {
          document.removeEventListener('fullscreenchange', fullscreenChangeHandler);
          window.removeEventListener('message', messageHandler);
        }
      });
      
      return {
        pdfDialogVisible,
        pdfUrl,
        openPDF,
        downloadPDF,
        getFilename,
        toggleFullscreen,
        zoomIn,
        zoomOut,
        fitToPage,
        isFullscreen,
        scale,
        pdfFrameRef,
        app
      };
    }
  };
  </script>
  
  <style scoped>
  .pdf-container {
    position: relative;
    border: 1px solid #e2e8f0;
    border-radius: 4px;
    overflow: hidden;
    background-color: #f8f9fa;
    height: 100%;
    cursor: pointer;
    transition: all 0.2s;
  }
  
  .pdf-container:hover {
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }
  
  .pdf-preview-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
    padding: 10px;
  }
  
  .pdf-preview-container i {
    color: #e53935;
    margin-bottom: 8px;
    font-size: 2.5rem;
  }
  
  .pdf-filename {
    font-size: 12px;
    color: #333;
    text-align: center;
    word-break: break-word;
    max-width: 100%;
  }
  
  .pdf-dialog-container {
    width: 100%;
    height: 1000px;
    overflow: hidden;
    background-color: #f0f0f0;
    display: flex;
    flex-direction: column;
  }
  
  .pdf-viewer {
    flex: 1;
    min-height: 0; /* 重要：防止内容溢出 */
    width: 100%;
    border: none;
    background-color: white;
  }
  
  :deep(.p-dialog-content) {
    padding: 0;
    display: flex;
    flex-direction: column;
    height: 100%;
  }
  
  :deep(.p-dialog-header) {
    padding: 0.75rem 1rem;
    background-color: #f8f9fa;
  }
  
  :deep(.p-dialog-content) {
    padding: 0;
    overflow: hidden;
    background-color: white;
  }
  
  :deep(.p-dialog-footer) {
    padding: 0.75rem 1rem;
    background-color: #f8f9fa;
  }
  
  /* 全屏模式下的样式 */
  :fullscreen .pdf-dialog-container,
  :-webkit-full-screen .pdf-dialog-container,
  :-moz-full-screen .pdf-dialog-container,
  :-ms-fullscreen .pdf-dialog-container {
    height: 100vh;
  }
  
  :fullscreen .pdf-viewer,
  :-webkit-full-screen .pdf-viewer,
  :-moz-full-screen .pdf-viewer,
  :-ms-fullscreen .pdf-viewer {
    height: calc(100vh - 100px);
  }
  </style>